<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>  
<!DOCTYPE HTML>
<html>
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chorme=1">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<title>文件管理</title>
	<link rel="stylesheet" type="text/css" href="${ROOT }/resource/css/global.css" media="all">
	
    <script type="text/javascript"  src="${ROOT}/resource/js/jquery-1.7.2.min.js"></script>   
    <script type="text/javascript"  src="${ROOT}/resource/js/file_manage.js"></script>   
	<script type="text/javascript" src="${ROOT}/resource/plugins/swfupload/swfupload.js"></script>
	<script type="text/javascript" src="${ROOT}/resource/plugins/swfupload/swfupload.queue.js"></script>
	<script type="text/javascript" src="${ROOT}/resource/plugins/swfupload/fileprogress.js"></script>
<style type="text/css">
object {
	width:65px;
	height:28px;
}
</style>	
<script type="text/javascript">
var root = '${ROOT}';//发布器项目根目录
window.onload = function() {
	upload1 = new SWFUpload({
		// Backend Settings
		upload_url: root+"/file/upload.do",
		post_params: {  //附带的表单参数
			"currentPath" : "${realtivePath}",
			"channelId" : "${channelInfo.id}",
			"JSESSIONID" : "<%=session.getId()%>"
		},
		// File Upload Settings
		file_size_limit : "102400",	// 100MB
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : "0",
		file_queue_limit : "100",
		
		file_queued_handler : fileQueuedFunction,//在文件选择窗关闭后，文件排队上传之前触发。
		file_queue_error_handler : fileQueueError,//在文件选择窗关闭后，文件排队发生错误时触发
		file_dialog_complete_handler : fileDialogCompleteHandler,//在文件选择窗关闭后，文件排队上传的过程中触发
		upload_error_handler : uploadError,//文件上传的过程中发生了错误触发的事件
		upload_success_handler : uploadSuccessHandler,//文件上传成功后触发的事件

		// Button settings
		button_image_url: root+"/resource/plugins/swfupload/images/button.png",
		button_width: "65",
		button_height: "29",
		button_placeholder_id: "spanButtonPlaceholder",
		button_text: '<span class="theFont" >上传文件</span>',
		button_text_style: ".theFont { font-weight:bold; color:white; }",
		button_text_left_padding: 3,
		button_text_top_padding: 6,
		
		// Flash Settings
		flash_url : root+"/resource/plugins/swfupload/swfupload.swf",

		custom_settings : {
			progressTarget : "fsUploadProgress1"
		},
		
		// Debug Settings
		debug: false
	});
}

var dirArr = [];//目录数组
var fileArr = [];//文件目录
var isMergeFile ;
//在文件选择窗关闭后，文件排队上传之前触发。
function fileQueuedFunction(file) {
	 isMergeFile = false;
	var fileName = file.name;
	var suffix = getSuffix(fileName);
	if(suffix == 'rar' || suffix == 'zip'){
		var pureFileName = fileName.substring(0 , fileName.lastIndexOf('.'));//不带后缀的文件名
		for(var i=0 ; i < dirArr.length ; i ++){
			if(dirArr[i] == pureFileName ){
				if(confirm('此目录已包含名为"' +pureFileName + '"的目录，是否合并该目录?')){
					 isMergeFile = true;
				}else{
					this.cancelUpload(file.id);
					this.debug('取消上传同名文件夹');
				}
				break;
			}
		}
	}else{//文件
		for(var i=0 ; i < fileArr.length ; i ++){
			if(fileArr[i] == fileName ){
				if(confirm('此文件"' +fileName + '"已存在，是否覆盖该文件?')){
					alert("文件覆盖，需要清除浏览缓存或强刷才能看到覆盖后的文件");
					 isMergeFile = true;
				}else{
					this.cancelUpload(file.id);
					this.debug('取消上传同名文件夹');
				}
				break;
			}
		}
	}
	
}
//取文件前缀
function getSuffix(fileName){
	var suffix = '';
	if(fileName && fileName.indexOf('.') > -1){
		suffix = fileName.substring(fileName.lastIndexOf('.')+1 , fileName.length).toLowerCase();
	}
	return suffix;
}

//文件上传成功后触发的事件
function uploadSuccessHandler(file, serverData) {
	var serverDataArr = serverData.split(';infoSeparator;');
	var fileHtml = '<li>';
	var isPic = serverDataArr[0];
	var basePicUrl = '${basePicUrl}';
	var baseHtmlUrl = '${baseHtmlUrl}';
	var basePicOnlineUrl = '${basePicOnlineUrl}';
//	basePicUrl = basePicOnlineUrl;
//	baseHtmlUrl = basePicOnlineUrl;
	var realtivePath = '${realtivePath}';
	var fileName = serverDataArr[1];
	var picUrl = basePicUrl +realtivePath +fileName;
	var htmlUrl = baseHtmlUrl +realtivePath +fileName;
	var nowDate = getDateStr(new Date());
	if( isPic == 'true'){
		fileHtml += '<a class="pic-name" href="'+picUrl+'" target="_blank" title="'+nowDate+'">'
						+'<img src="'+picUrl+'" alt="'+fileName+'"></a>'
						+'<a href="'+picUrl+'" class="name" target="_blank">'+fileName+'</a>';
	}else{
		var suffix = getSuffix(fileName);
		if(suffix == 'rar' || suffix == 'zip'){
			var fileName = fileName.substring( 0 , fileName.lastIndexOf('.'));
			realtivePath = realtivePath + fileName+'/';
			fileHtml += '<a class="pic-name" href="/file/fileManage.do?toDirPath='+realtivePath+'" title="'+nowDate+'">'+
				'<img src="'+root+'/resource/images/filemanager/folder2.png" alt="head"></a>'+
				'<a href="/file/fileManage.do?toDirPath='+realtivePath+'" class="name" >'+fileName+'</a>';
			location.reload();
			return ;	
		}else{
			fileHtml += '<a class="pic-name" href="'+htmlUrl+'" target="_blank" title="'+nowDate+'">'
			+ '<img src="${ROOT}/resource/images/filemanager/'+suffix+'.png" alt="'+fileName+'"></a>'
			+ '<a href="'+htmlUrl+'" class="name" target="_blank">'+fileName+'</a>';
		}
	}
	fileHtml += '<a href="javascript:deleteFile(\''+fileName+'\')" class="close">×</a></li>';
	if(isMergeFile){//如果是覆盖的目录，则不显示
		return ;
	}
	$('#fileList').append(fileHtml);
}

/**
 * 输入date，返回字符串的格式为:yyyy-mm-dd hh:mm
 */
function getDateStr(date){
	return date.getFullYear() + '-' + addZero(date.getMonth()+1) 
		+ '-' +addZero(date.getDate())+' ' + addZero(date.getHours()) + ':' + addZero(date.getMinutes());
}
/**
 * 小于10，补上0
 */
function addZero(number){
	if(number < 10 ){
		return '0'+number;
	}
	return number;
}

//按"回车"键触发查询事件
function bindSearch(){
	if((event.ctrlKey)||(event.keyCode==13)){
		searchSubmit();
	}
}
$(function (){
	$(".showImage").mouseover(function(e){
			var imgSrc = $(this).attr('href');
			//创建数据显示div元素
			var tipDIV = "<div id='preViewTip'><img src='"+imgSrc+"' height='90' width='130'></div>";
			//追加到文档中
			$("body").append(tipDIV);
			$("#preViewTip").css({
				"top": (e.pageY - 90) + "px",
				"left": (e.pageX + 10) + "px",
				"position":"absolute",
				"border":"1px solid #333",
				"background":"#f7f5d1",
				"padding":"1px"
			}).show("fast");
			
		}).mouseout(function(){
			$("#preViewTip").remove();//移除
		}).mousemove(function(e){
			$("#preViewTip").css({
				"top": (e.pageY - 90) + "px",
				"left": (e.pageX + 10) + "px",//跟随光标移动
			})
		});
	
});
</script>	
</head>
<body onkeydown="bindSearch()">
	<div class="main-content">
		<!--头部动作条 start-->
		<jsp:include page="/head.do"></jsp:include>
		<!--头部动作条 end-->

		<div class="blank10"></div>
		<!--文件管理 start-->
		<div class="doc-manage">
			<div class="search-bar">
						当前路径：
						<a href="${ROOT}/file/fileManage.do" class="addr-url">
						<strong>root</strong></a>/
						<c:set var="paths" value="${fn:split(realtivePath, '/')}" />
						<c:set var="toDirpath" value="/" />
						<c:forEach var="path" items="${paths}" varStatus="idx" begin="0"><c:set var="toDirpath" value="${toDirpath}${path}/"/><a href="${ROOT}/file/fileManage.do?toDirPath=${toDirpath}" class="addr-url"><strong>${path}/</strong></a></c:forEach>
			</div>
			<div class="search-bar">
				
				<input class="style-input fixwidth-l" type="text" placeholder="请输入查询的关键字"   name="tempSearchKey" id="tempSearchKey" value="${param.searchKey}" />
				<a href="javascript:searchSubmit()" class="go-search-bt c-green-bt mlm">搜索</a>
				<input type="button" class="go-search-bt c-green-bt mlm" onclick="javascript:createFolder();" value="创建目录" />
				&nbsp;&nbsp;&nbsp;&nbsp;
				<div style="display:inline;position:relative ;top:12px;">
					<input type="button"  id="spanButtonPlaceholder"  />
				</div>
				&nbsp;&nbsp;&nbsp;&nbsp;
				<!-- 
					<input type="button" class="u-inputBtn mlm" onclick="javascript:chooseFile();" value="上传文件">
				 -->
				
				
				<form action="/file/upload.do" id="uploadForm" enctype="multipart/form-data"  method="post" >
						<input class="style-input fixwidth-l" type="file" name="toUploadFile" style="display:none" id="toUploadFile" onchange="uploadFile()" />
						<input type="hidden" value="${realtivePath}"  name="currentPath" id="currentPath" />
				</form>
				<form action="/file/searchFile.do" method="get" name="searchForm" id="searchForm" >
					<input class="style-input fixwidth-l" type="hidden" name="searchKey" id="searchKey" value="${param.searchKey}" />
					<input type="hidden" name="currentPath" value="${realtivePath}" />
					<input type="hidden" name="parentRealtivePath" value="${parentRealtivePath}" />
				</form>

			</div>
			<div class="blank10"></div>
			<ul class="file-list" id="fileList">
				<c:forEach var="file" items="${listFiles}" varStatus="idx" begin="0">
					<c:if test="${ not empty file.name}">
						<c:if test="${file.isDirectory}">
							<c:if test="${!(fn:length(file.name)==4 && fn:toLowerCase(file.name)==fn:toUpperCase(file.name))}"> <%//文件夹命名为“MMdd”都隐藏起来， 这些都不管理，属于发文章上传的图片 %>
								<li>
									<a class="pic-name" href="/file/fileManage.do?toDirPath=${realtivePath}${file.name}/" title="${file.lastModified}"><img src="${ROOT}/resource/images/filemanager/folder2.png" alt="${file.name}"></a>
									<a href="/file/fileManage.do?toDirPath=${realtivePath}${file.name}/" class="name" >${file.name}</a>
									<a href="javascript:deleteFile('${file.name}')" class="close">×</a>
								</li>
							</c:if>
							<script type="text/javascript">
									dirArr.push('${file.name}');
							</script>
						</c:if>
						<c:if test="${!file.isDirectory}">
							<li>
								<!-- /s/目录的文件需要特殊处理 -->
								<c:if test="${fn:indexOf(realtivePath , '/s/') > -1}">
									<a class="pic-name" href="${baseHtmlOnlineUrl}${realtivePath}${file.name}" target="_blank" title="${file.lastModified}">
										<img src="${ROOT}/resource/images/filemanager/${fn:toLowerCase( fn:substringAfter(file.name, ".")  )}.png" alt="${file.name}">
								    </a>
								    <a href="${baseHtmlOnlineUrl}${realtivePath}${file.name}" class="name" target="_blank">${file.name}</a>
								</c:if>
								
								<!-- 非/s/目录的文件 -->
								<c:if test="${fn:indexOf(realtivePath , '/s/') == -1}">
										<c:if test="${file.pic}">
												<a class="pic-name showImage" href="${basePicOnlineUrl}${realtivePath}${file.name}" target="_blank"
														 title="${file.lastModified}">
													<img src="${ROOT}/resource/images/filemanager/${fn:toLowerCase(fn:substringAfter(file.name, ".") )}.png" alt="${file.name}">
												</a>
												<a href="${basePicOnlineUrl}${realtivePath}${file.name}" class="name" target="_blank">${file.name}</a>
										</c:if>
										<c:if test="${!file.pic}">
												<a class="pic-name" href="${baseHtmlOnlineUrl}${realtivePath}${file.name}" target="_blank"
													 title="${file.lastModified}">
													<img src="${ROOT}/resource/images/filemanager/${fn:toLowerCase(fn:substringAfter(file.name, ".") )}.png" alt="${file.name}">
												</a>
												<a href="${baseHtmlOnlineUrl}${realtivePath}${file.name}" class="name" target="_blank">${file.name}</a>
										</c:if>
								</c:if>
									<a href="javascript:deleteFile('${file.name}')" class="close">×</a>
							</li>
							<script type="text/javascript">
								fileArr.push('${file.name}');
							</script>
						</c:if>
					</c:if>
				</c:forEach>
			</ul>
		    <div class="blank20"></div>
		</div>
		<!--文件管理 end-->

	</div>
<form name="form_mkdir" id="form_mkdir" method="get" action="/file/createFolder.do" >
     <input type="hidden" name="realtivePath"  value="${realtivePath}" />
     <input type="hidden" name="dirName"   />
</form>	
<script type="text/javascript">
function deleteFile(deletePath){
	if(confirm('确定要删除此文件？只删除本地，不会删除外网的文件')){
		location.href = '/file/deleteFile.do?deletePath='+deletePath+'&realtivePath=${realtivePath}';
	}
}
//搜索文件
function searchSubmit(){
	var searchKey = $("#tempSearchKey").val()
	if(""==searchKey){
		//alert("请输入查询的关键字!");
	}else{
		$("#searchKey").val(searchKey);
		$('#searchForm').submit();
	}
}

//选择文件
function chooseFile(){
	//正在搜索中，禁止上传
	if('${realtivePath}' == ''){
		return ;
	}
	$('#toUploadFile').click();
	
}

//上传文件
function uploadFile(){
	//正在搜索中，禁止上传
	if('${realtivePath}' == ''){
		return ;
	}
	if(isLegitimateFile($('#toUploadFile').val())){
		$('#uploadForm').submit();
	}
	
}

//判断是否是合法的文件名
function isLegitimateFile(filename)
{
	var fname = trimStr( filename );
	if(fname.indexOf("\\")!=-1){
		fname = fname.substring(fname.lastIndexOf("\\")+1);
	}
	if(fname.length > 100){
		alert('上传失败:文件名过长');
		return false;
	}
	var reg = new RegExp("(\.(jpg|jpeg|gif|js|html|htm|png|bmp|css|xml|mp3|wav|wmv|flv|txt|shtml|ico)){1}$","i");
    if( fname=="" || !reg.test(fname) ){
		alert('只能上传(jpg|jpeg|gif|js|html|htm|png|bmp|css|xml|mp3|wav|wmv|flv|txt|shtml|ico)类的文件');
    	return false;  
    }
    return true;
}
//去掉前后空格
function trimStr( text )
{
	return (text || "").replace( /^\s+|\s+$/g, "" );
}

//创建目录
function createFolder(msg) {
	var folderName = null;
	var listFileStr  = '${listFileStr}';
    var imsg = (msg==null)?"":msg;
    folderName = prompt("请输入目录名(允许输入完整路径创建目录)", imsg);
	if(null==folderName)	{//取消
       return;
	}else if(""==folderName){
       alert("目录名称不能为空");
       createFolder();
       return;
	}else if(!( /^([a-z0-9_\-\/])+$/ig.test(folderName))){
		alert("目录名称只能以小写的字母,下划线和数字组成");
		createFolder(folderName);
	    return;
	}else if(( /^([0-9]){4}$/ig.test(folderName))){
		alert("以年月为名(如1304)的目录会自动隐藏,请勿创建此类目录.");
		createFolder(folderName);
	    return;
	}else if(listFileStr.indexOf(folderName + ',')>-1){
		if(confirm("提示目录已存在，是否打开该目录？")){
			location.href = '/file/fileManage.do?toDirPath=${realtivePath}'+folderName+'/';
		}
	}
	var fobj = document.getElementById("form_mkdir");
	if(fobj!=null)
	{
		fobj.dirName.value = folderName;
		fobj.submit();
	}
}
</script>
</body>
</html>